﻿using B.S.DataBase.Domain;
using B.S.DataBase.ErrorCode;
using B.S.DataBase.Infrastructure;
using B.S.DataBase.Write.API.Application.Commands.Update;
using MediatR;

namespace B.S.DataBase.Write.API.Application.Handlers.UpdateHandler
{
    public class DeletedProductHandler : IRequestHandler<DeletedProductCommand, APIResult<int>>
    {
        private readonly IBaseRepository<Product> productRepository;

        public DeletedProductHandler(IBaseRepository<Product> productRepository)
        {
            this.productRepository = productRepository;
        }

        public async Task<APIResult<int>> Handle(DeletedProductCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();

            var entity = productRepository.GetAllAsync().FirstOrDefault(x => x.Id == request.Id);

            if (entity != null)
            {
                entity.IsDeleted = true;
                var dto = productRepository.Update(entity).Result;
                if (dto > 0)
                {
                    result.Code = APIEnums.Success;
                    result.Meg = "删除成功";
                    result.Data = dto;
                }
                else
                {
                    result.Code = APIEnums.Fail;
                    result.Meg = "删除失败";
                    return await Task.FromResult(result);
                }

            }

            return await Task.FromResult(result);
        }
    }
}
